/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.service.loader.support.creator;

import org.jrose.entity.config.InitialAttribute;
import org.jrose.entity.data.Attribute;
import org.jrose.entity.data.Role;
import org.jrose.service.loader.support.LoaderProvider;

import static org.jrose.core.util.RandomUtils.nextInt;

public class AttributeCreator extends AbstractCreator<Attribute> {
    private final Attribute attribute;

    public AttributeCreator(LoaderProvider loaderProvider, Role role) {
        super(loaderProvider);
        InitialAttribute initialAttribute = loaderProvider.getInitialAttributeLoader().load();
        attribute = newAttribute(role.getId(), initialAttribute);
    }

    @Override
    public Attribute fin() {
        loaderProvider.getAttributePersistence().persist(attribute);
        return attribute;
    }

    private Attribute newAttribute(Long roleId, InitialAttribute initialAttribute) {
        Attribute attribute = Attribute.newInstance(roleId);
        attribute.setMaxHealth(nextInt(initialAttribute.getLoMaxHealth(), initialAttribute.getHiMaxHealth()));
        attribute.setHealth(attribute.getMaxHealth());
        attribute.setMaxMana(nextInt(initialAttribute.getLoMaxMana(), initialAttribute.getHiMaxMana()));
        attribute.setMana(attribute.getMaxMana());
        attribute.setAttack(nextInt(initialAttribute.getLoAttack(), initialAttribute.getHiAttack()));
        attribute.setDefense(nextInt(initialAttribute.getLoDefense(), initialAttribute.getHiDefense()));
        attribute.setSpiritAttack(nextInt(initialAttribute.getLoSpiritAttack(), initialAttribute.getHiSpiritAttack()));
        attribute.setSpiritDefense(nextInt(initialAttribute.getLoSpiritDefense(), initialAttribute.getHiSpiritDefense()));
        attribute.setSpeed(nextInt(initialAttribute.getLoSpeed(), initialAttribute.getHiSpeed()));
        return attribute;
    }
}
